<!DOCTYPE html>
<html lang="zh-CN" id="html-element">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MockData API 文档</title>
    <link rel="stylesheet" type="text/css" href="./css/css2.css">
    <link rel="stylesheet" type="text/css" href="./css/all.css">
    <link rel="stylesheet" type="text/css" href="./css/main.css">
</head>
<body>
<!-- 顶部导航栏 -->
<header class="header">
    <div class="container header-content">
        <div class="logo">
            <i class="fas fa-code-fork logo-icon"></i>
            <span class="logo-text">MockData</span>
        </div>
        <div class="header-actions">
            <button class="theme-toggle" id="theme-toggle">
                <i class="fas fa-moon"></i>
            </button>
        </div>
    </div>
</header>

<!-- 主内容区 -->
<main class="container">
    <!-- 搜索框 -->
    <div class="search-container" style="display: none;">
        <div class="search-box">
            <i class="fas fa-search search-icon"></i>
            <input type="text" class="search-input" placeholder="搜索API..." id="search-input">
        </div>
    </div>

    <!-- 服务概览 -->
    <section class="overview">
        <h1 class="overview-title">API 文档中心</h1>
        <p class="overview-desc">基于 Express 和 Mock.js 构建的模拟数据服务，为前端开发和测试提供便捷的接口模拟</p>

        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon primary">
                    <i class="fas fa-link"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-label">服务地址</div>
                    <div class="stat-value" id="service-url">--</div>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon secondary">
                    <i class="fas fa-list-ul"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-label">API 总数</div>
                    <div class="stat-value" id="api-count">--</div>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon success">
                    <i class="fas fa-folder-open"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-label">分类数</div>
                    <div class="stat-value" id="category-count">--</div>
                </div>
            </div>
        </div>
    </section>

    <!-- 分类部分 -->
    <section>
        <h2 class="section-title">
            <span>API 分类</span>
        </h2>
        <div class="categories-grid" id="category-container">
            <div class="loading">
                <i class="fas fa-spinner loading-spinner"></i>
                <p>加载分类中...</p>
            </div>
        </div>
    </section>

    <!-- API列表 -->
    <section>
        <div class="section-title">
            <div>
                <span id="current-category">全部</span>
                <span class="text-sm text-gray-500" id="current-api-count">--个接口</span>
            </div>
            <!-- 新增的迷你搜索框 -->
            <div class="mini-search-container">
                <div class="mini-search-box">
                    <i class="fas fa-search mini-search-icon"></i>
                    <input type="text" class="mini-search-input" placeholder="搜索API..." id="mini-search-input">
                </div>
            </div>
        </div>

        <div class="api-list" id="api-container">
            <div class="loading">
                <i class="fas fa-spinner loading-spinner"></i>
                <p>加载API列表中...</p>
            </div>
        </div>
    </section>
</main>

<!-- 页脚 -->
<footer>
    <div class="container">
        <p>© 2025 MockData | 为前端开发提供便捷的模拟数据服务</p>
    </div>
</footer>

<!-- API详情模态框 -->
<div class="modal-overlay" id="detail-modal">
    <div class="modal">
        <div class="modal-header">
            <h3 class="modal-title" id="modal-title">
                <span class="api-method get">GET</span>
                <span>/api/users</span>
            </h3>
            <button class="close-btn" id="close-modal">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="modal-body" id="modal-content">
            <!-- 内容将通过JavaScript动态生成 -->
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        // 动态获取并设置服务地址
        const serviceUrlElement = document.getElementById('service-url');
        const baseUrl = window.location.origin;
        serviceUrlElement.textContent = baseUrl;

        // 确保模态框中的URL示例也使用动态地址
        document.addEventListener('click', (event) => {
            if (event.target.closest('.api-item')) {
                setTimeout(() => {
                    const urlBoxes = document.querySelectorAll('.url-box');
                    urlBoxes.forEach(box => {
                        if (box.textContent.startsWith('http://localhost:3000')) {
                            box.textContent = baseUrl + box.textContent.substring(21);
                        }
                    });
                }, 100); // 给模态框渲染留出时间
            }
        });

        // 主题切换功能
        const htmlElement = document.getElementById('html-element');
        const themeToggle = document.getElementById('theme-toggle');

        // 检查本地存储的主题偏好
        const savedTheme = localStorage.getItem('theme');
        if (savedTheme === 'dark') {
            htmlElement.setAttribute('data-theme', 'dark');
            if (themeToggle) {
                themeToggle.querySelector('i').className = 'fas fa-sun';
            }
        }

        // 主题切换事件
        if (themeToggle) {
            themeToggle.addEventListener('click', () => {
                const isDark = htmlElement.getAttribute('data-theme') === 'dark';
                const themeIcon = themeToggle.querySelector('i');

                if (isDark) {
                    htmlElement.removeAttribute('data-theme');
                    localStorage.setItem('theme', 'light');
                    themeIcon.className = 'fas fa-moon';
                } else {
                    htmlElement.setAttribute('data-theme', 'dark');
                    localStorage.setItem('theme', 'dark');
                    themeIcon.className = 'fas fa-sun';
                }
            });
        }

        const apiContainer = document.getElementById('api-container');
        const categoryContainer = document.getElementById('category-container');
        const apiCountElement = document.getElementById('api-count');
        const categoryCountElement = document.getElementById('category-count');
        const currentCategoryElement = document.getElementById('current-category');
        const currentApiCountElement = document.getElementById('current-api-count');
        const searchInput = document.getElementById('search-input');
        const miniSearchInput = document.getElementById('mini-search-input');
        const detailModal = document.getElementById('detail-modal');
        const closeModal = document.getElementById('close-modal');
        const modalTitle = document.getElementById('modal-title');
        const modalContent = document.getElementById('modal-content');

        // 存储所有API数据
        let allApis = [];
        // 当前选中的分类
        let currentCategory = 'all';
        // 当前过滤的API
        let filteredApis = [];

        // 获取API列表
        fetch('/api/docs')
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取API列表失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.code === 200 && data.data && data.data.length > 0) {
                    allApis = data.data;
                    filteredApis = [...allApis];

                    // 渲染分类卡片
                    renderCategories(allApis);

                    // 渲染API列表
                    renderApiList(filteredApis);

                    // 更新统计信息
                    apiCountElement.textContent = allApis.length;
                    currentApiCountElement.textContent = `${filteredApis.length} 个接口`;
                } else {
                    showEmptyState(apiContainer, '未找到API接口');
                }
            })
            .catch(error => {
                console.error('获取API列表失败:', error);
                showErrorState(apiContainer, `加载API列表失败: ${error.message}`);
            });

        // 渲染分类卡片
        function renderCategories(apis) {
            // 收集所有分类
            const categories = new Set();
            apis.forEach(api => {
                if (api.group) {
                    categories.add(api.group);
                }
            });

            // 转换为数组并排序
            const categoryList = Array.from(categories).sort();

            // 添加"全部"分类
            categoryList.unshift('all');

            // 更新分类计数
            categoryCountElement.textContent = categoryList.length - 1;

            // 生成HTML
            let html = '';

            categoryList.forEach(category => {
                const isActive = category === currentCategory;
                const apiCount = category === 'all'
                    ? apis.length
                    : apis.filter(api => api.group === category).length;

                html += `
                        <div class="category-card ${isActive ? 'active' : ''}" data-category="${category}">
                            <div class="category-header">
                                <div class="category-name">
                                    <i class="fas fa-folder"></i>
                                    <span>${category === 'all' ? '全部' : category}</span>
                                </div>
                                <span class="category-count">${apiCount}</span>
                            </div>
                        </div>
                    `;
            });

            categoryContainer.innerHTML = html;

            // 添加点击事件监听
            document.querySelectorAll('.category-card').forEach(card => {
                card.addEventListener('click', () => {
                    const category = card.getAttribute('data-category');
                    filterByCategory(category);
                });
            });
        }

        // 按分类过滤API
        function filterByCategory(category) {
            currentCategory = category;

            // 更新分类卡片样式
            document.querySelectorAll('.category-card').forEach(card => {
                if (card.getAttribute('data-category') === category) {
                    card.classList.add('active');
                } else {
                    card.classList.remove('active');
                }
            });

            // 更新当前分类标题
            currentCategoryElement.textContent = category === 'all' ? '全部' : category;

            // 过滤API
            if (category === 'all') {
                filteredApis = [...allApis];
            } else {
                filteredApis = allApis.filter(api => api.group === category);
            }

            // 更新API计数
            currentApiCountElement.textContent = `${filteredApis.length} 个接口`;

            // 应用搜索（如果有搜索词）
            const searchTerm = searchInput.value.toLowerCase().trim() || miniSearchInput.value.toLowerCase().trim();
            if (searchTerm) {
                applySearch(searchTerm);
            } else {
                // 重新渲染API列表
                renderApiList(filteredApis);
            }
        }

        // 渲染API列表
        function renderApiList(apis) {
            if (apis.length === 0) {
                showEmptyState(apiContainer, '此分类下没有API接口');
                return;
            }

            let html = '';

            apis.forEach(api => {
                const methodColor = getMethodClass(api.method);
                const shortDescription = api.description || getDefaultDescription(api.path, api.method);

                html += `
                        <div class="api-item" data-path="${api.path}" data-method="${api.method}">
                            <div class="api-header">
                                <span class="api-method ${methodColor}">${api.method}</span>
                                <span class="api-path">${api.path}</span>
                            </div>
                            <p class="api-desc">${shortDescription}</p>
                            <div class="api-actions">
                                <button class="copy-btn" data-clipboard-text="${api.path}">
                                    <i class="far fa-copy"></i> 复制
                                </button>
                            </div>
                        </div>
                    `;
            });

            apiContainer.innerHTML = html;

            // 添加复制按钮功能
            document.querySelectorAll('.copy-btn').forEach(button => {
                button.addEventListener('click', (e) => {
                    e.stopPropagation();
                    const text = button.getAttribute('data-clipboard-text');
                    navigator.clipboard.writeText(text).then(() => {
                        const icon = button.querySelector('i');
                        icon.className = 'fas fa-check';
                        button.innerHTML = `${icon.outerHTML} 已复制`;

                        setTimeout(() => {
                            button.innerHTML = '<i class="far fa-copy"></i> 复制';
                        }, 1500);
                    });
                });
            });

            // 添加点击事件监听
            document.querySelectorAll('.api-item').forEach(item => {
                item.addEventListener('click', () => {
                    const path = item.getAttribute('data-path');
                    const method = item.getAttribute('data-method');
                    showApiDetail(path, method);
                });
            });
        }

        // 获取方法对应的样式类
        function getMethodClass(method) {
            switch (method.toUpperCase()) {
                case 'GET': return 'get';
                case 'POST': return 'post';
                case 'PUT': return 'put';
                case 'DELETE': return 'delete';
                default: return '';
            }
        }

        // 获取默认描述
        function getDefaultDescription(path, method) {
            if (path.includes('/user')) {
                if (path.endsWith('/user')) {
                    return method === 'GET' ? '获取用户列表' : '创建用户';
                } else {
                    return method === 'GET' ? '获取用户详情' :
                        method === 'PUT' ? '更新用户信息' : '删除用户';
                }
            } else if (path.includes('/product')) {
                if (path.endsWith('/product')) {
                    return method === 'GET' ? '获取商品列表' : '创建商品';
                } else {
                    return method === 'GET' ? '获取商品详情' :
                        method === 'PUT' ? '更新商品信息' : '删除商品';
                }
            }
            return '未知接口';
        }

        // 显示API详情
        function showApiDetail(path, method) {
            const api = allApis.find(api => api.path === path && api.method === method);
            if (!api) return;

            // 设置模态框标题
            const methodClass = getMethodClass(api.method);
            modalTitle.innerHTML = `
                    <span class="api-method ${methodClass}">${api.method}</span>
                    <span>${api.path}</span>
                `;

            // 生成详情内容
            let content = `
                    <div class="modal-section">
                        <h4 class="modal-section-title">接口描述</h4>
                        <p>${api.description || getDefaultDescription(api.path, api.method)}</p>
                    </div>

                    <div class="modal-section">
                        <h4 class="modal-section-title">请求 URL</h4>
                        <div class="url-box">
                            ${baseUrl}${api.path}
                        </div>
                    </div>
                `;

            // 添加参数部分
            if (api.parameters && api.parameters.length > 0) {
                content += `
                        <div class="modal-section">
                            <h4 class="modal-section-title">请求参数</h4>
                            <table class="params-table">
                                <thead>
                                    <tr>
                                        <th>参数名</th>
                                        <th>类型</th>
                                        <th>是否必需</th>
                                        <th>描述</th>
                                    </tr>
                                </thead>
                                <tbody>
                    `;

                api.parameters.forEach(param => {
                    content += `
                            <tr>
                                <td class="font-mono">${param.name}</td>
                                <td>${param.type}</td>
                                <td>${param.required ? '<span style="color: var(--danger)">是</span>' : '<span style="color: var(--gray-500)">否</span>'}</td>
                                <td>${param.description || '-'}</td>
                            </tr>
                        `;
                });

                content += `
                                </tbody>
                            </table>
                        </div>
                    `;
            }

            // 添加响应示例部分
            content += `
                    <div class="modal-section">
                        <h4 class="modal-section-title">响应示例</h4>
                        <div class="response-box" id="response-example">
                            加载中...
                        </div>
                    </div>
                `;

            modalContent.innerHTML = content;

            // 显示模态框
            detailModal.classList.add('active');

            // 获取并显示响应示例
            fetchResponseExample(api.path, api.method);
        }

        // 获取响应示例
        function fetchResponseExample(path, method) {
            const responseElement = document.getElementById('response-example');

            fetch(path, { method })
                .then(response => response.json())
                .then(data => {
                    responseElement.textContent = JSON.stringify(data, null, 2);
                })
                .catch(error => {
                    responseElement.textContent = `获取响应示例失败: ${error.message}`;
                    responseElement.style.color = 'var(--danger)';
                });
        }

        // 关闭模态框
        closeModal.addEventListener('click', () => {
            detailModal.classList.remove('active');
        });

        // 点击模态框外部关闭
        detailModal.addEventListener('click', (e) => {
            if (e.target === detailModal) {
                detailModal.classList.remove('active');
            }
        });

        // 搜索功能
        function applySearch(term) {
            if (!term) {
                renderApiList(filteredApis);
                return;
            }

            const searchResults = filteredApis.filter(api =>
                api.path.toLowerCase().includes(term) ||
                (api.description && api.description.toLowerCase().includes(term))
            );

            renderApiList(searchResults);
        }

        // 监听两个搜索框的输入事件
        searchInput.addEventListener('input', (e) => {
            // 同步两个搜索框的值
            miniSearchInput.value = e.target.value;
            applySearch(e.target.value.toLowerCase());
        });

        miniSearchInput.addEventListener('input', (e) => {
            // 同步两个搜索框的值
            searchInput.value = e.target.value;
            applySearch(e.target.value.toLowerCase());
        });

        // 显示空状态
        function showEmptyState(container, message) {
            container.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-inbox empty-icon"></i>
                        <p>${message}</p>
                    </div>
                `;
        }

        // 显示错误状态
        function showErrorState(container, message) {
            container.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-exclamation-circle empty-icon" style="color: var(--danger)"></i>
                        <p>${message}</p>
                    </div>
                `;
        }
    });
</script>
</body>
</html>